package org.liveboardgames.agricola.control.delegates.action.processor
{
    import org.liveboardgames.agricola.control.delegates.helper.GameHelper;
    import org.liveboardgames.agricola.model.AgricolaModelLocator;
    import org.liveboardgames.agricola.model.PopupModel;
    import org.liveboardgames.agricola.model.enums.ResourceTypeEnum;
    import org.liveboardgames.agricola.vo.action.Action;
    import org.liveboardgames.agricola.vo.common.Target;
    import org.liveboardgames.agricola.vo.farm.Farm;
    import org.liveboardgames.agricola.vo.player.Player;
    import org.liveboardgames.common.dictionary.collections.IMap;
    
    public class StableActionProcessor extends ActionProcessor
    {
        private var cost:IMap;
        
        private var player:Player;
        
        public function StableActionProcessor(action:Action)
        {
            super(action);
        }
        
        override public function execute():void
        {
            var target:Target = action.target
            if (target is Player)
            {
                player = target as Player;
                
                // The cost of one stable
                cost = action.cost
                var costInWood:int = cost.getValue(ResourceTypeEnum.WOOD);
                
                // The number of stables that can be constructed is limited by the 
                // number of maximum stables left and the number of woods.
                var farm:Farm = player.farm
                var resources:IMap = farm.resources;
                var woodLeft:int = 0;
                if (resources != null)
                {
                    woodLeft = resources.getValue(ResourceTypeEnum.WOOD);
                }
                
                // remaingin stables, how much can offord and how many the action allows
                var remainingStables:int = GameHelper.getRemainingStables(farm);
                
                var allowedByAction:int = action.numberOfUses;
                if (allowedByAction == 0)
                {
                    allowedByAction = GameHelper.MAX_STABLES;
                }
                
                var numberOfAllowedStable:int = Math.min(Math.floor(woodLeft / costInWood), remainingStables, allowedByAction);
                
                AgricolaModelLocator.getInstance().popups.currentActionPopupIndex = PopupModel.POPUP_BUILD_STABLE_INDEX;
                AgricolaModelLocator.getInstance().popups.numberOfStablesToBuild = numberOfAllowedStable;
                AgricolaModelLocator.getInstance().popups.stableColor = player.color;
                AgricolaModelLocator.getInstance().popups.cost = cost;
            }
            else
            {
                trace("not supported target " + target);
            }
        }
    }
}